package cc.catface.service;

import cc.catface.common.output.Result;
import cc.catface.dao.base.CommonINDTO;
import cc.catface.dao.biz.ad.AdChannel;
import cc.catface.dao.biz.ad.AdChannelLabel;
import cc.catface.dao.biz.ad.AdLabel;
import cc.catface.dao.biz.ad.dto.ListLabelChannelINDTO;
import cc.catface.dao.biz.ad.dto.ListLabelChannelOUTDTO;
import cc.catface.dao.biz.ad.mapper.AdChannelLabelMapperServiceImpl;
import cc.catface.dao.biz.ad.mapper.AdChannelMapperServiceImpl;
import cc.catface.dao.biz.ad.mapper.AdLabelMapperServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdChannelServiceImpl implements AdChannelService {
    @Autowired
    private AdLabelMapperServiceImpl adLabelMapperService;
    @Autowired
    private AdChannelLabelMapperServiceImpl adChannelLabelMapperService;
    @Autowired
    private AdChannelMapperServiceImpl adChannelMapperService;

    @Override
    public Result<List<ListLabelChannelOUTDTO>> listLabelChannel(ListLabelChannelINDTO in) {
        List<ListLabelChannelOUTDTO> outs = new ArrayList<>();

        //所有标签
        List<AdLabel> adLabels = adLabelMapperService.list();
        adLabels.forEach(adLabel -> {
            //组装标签信息
            ListLabelChannelOUTDTO out = new ListLabelChannelOUTDTO();
            out.setName(adLabel.getName());
            out.setType(adLabel.getType());
            out.setCreatedTime(adLabel.getCreatedTime());

            //组装该标签下的频道列表
            long labelId = adLabel.getId();
            QueryWrapper<AdChannelLabel> adChannelLabelQueryWrapper = new QueryWrapper<>();
            adChannelLabelQueryWrapper.eq("label_id", labelId);
            List<AdChannelLabel> adChannelLabels = adChannelLabelMapperService.list(adChannelLabelQueryWrapper);
            List<AdChannel> adChannels = new ArrayList<>();
            adChannelLabels.forEach(adChannelLabel -> {
                adChannels.add(adChannelMapperService.getById(adChannelLabel.getChannelId()));
            });
            out.setAdChannels(adChannels);

            outs.add(out);
        });

        return Result.success(outs);
    }

    @Override
    public Result<List<AdChannel>> listChannel(CommonINDTO in) {
        return Result.success(adChannelMapperService.list());
    }
}
